﻿/*
   Copyright 2014 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using Flower.Directory.Scripting.DirectoryEntries;
using Flower.Services;
using Flower.Services.Data;
using Jurassic;
using Jurassic.Library;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;

namespace Flower.Directory.Scripting.Functions.Processes
{
    internal class SaveState : ClrFunction
    {
        public SaveState(ScriptEngine engine)
            : base(engine.Function.InstancePrototype, "__saveState", engine.Function.InstancePrototype)
        {
        }

        [JSCallFunction]
        public void Exec(string pid, StateObject state)
        {
            try
            {
                IDirectory dir = Engine.GetDirectory();

                Exec(dir, pid, (State)state.Entry);
            }
            catch (JavaScriptException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new JavaScriptException(Engine, "Error", ex.Message, ex);
            }
        }

        [ClrScript]
        public static void Exec(IDirectory dir, string pid, State state)
        {
            Util.DemandLock.Acquire(pid);

            string statePath = string.Concat(dir.GetPathById(pid), "/", state.Name);

            DirectoryEntryInfo proc = dir.GetInfo(pid);

            if (proc == null) return;

            var acl = new List<AccessControlEntry>();

            foreach (AccessControlEntry procAcl in proc.AccessControlList)
            {
                acl.Add
                (
                    new AccessControlEntry
                    {
                        Role = procAcl.Role,
                        Permission = Permission.Read
                    }
                );
            }

            state.AccessControlList = acl;

            try
            {
                dir.Save(pid, state);
            }
            catch (FaultException<DirectoryFault> flt)
            {
                // Ignoring duplicates.
                if (flt.Detail.Code != DirectoryFaultCode.NameCollision)
                {
                    throw;
                }
            }
        }
    }
}
